<?php
if (!isset($common)) require_once 'common.php';

class Coordenadas
{
	private $coordx;
	private $coordy;
	
	function __construct($x, $y) {
      	$this->coordx = $x;
      	$this->coordy = $y;
   }

	public function setCoord($x, $y)
	{
		$this->coordx = $x;
		$this->coordy = $y;
	}
	
	public function getCoordX() {
		return $this->coordx;
	}
	
	public function getCoordY() {
		return $this->coordy;
	}
}

class Box
{
	private $box;
	private $boxLvl;
	
	function __construct($box, $boxLvl) 
	{
      	$this->box = $box;
      	$this->boxLvl = $boxLvl;
   }

	public function setBox($box, $boxLvl)
	{
		$this->box = $box;
		$this->boxLvl = $boxLvl;
	}
	
	public function getBox() 
	{
		return $this->box;
	}
	
	public function getBoxLvl() 
	{
		return $this->boxLvl;
	}
}

class Resources
{
	private $grano;
	private $hierro;
	private $oro;
	private $madera;
	
	function __construct($grano, $hierro, $oro, $madera) 
	{
      	$this->grano = $grano;
      	$this->hierro = $hierro;
      	$this->oro = $oro;
      	$this->madera = $madera;
   }
	
	public function getGrano() 
	{
		return $this->grano;
	}
	
	public function getHierro() 
	{
		return $this->hierro;
	}
	
	public function getOro() 
	{
		return $this->oro;
	}
	
	public function getMadera() 
	{
		return $this->madera;
	}
	
	public function setGrano($grano) 
	{
		$this->grano = $grano;
	}
	
	public function setHierro($hierro) 
	{
		$this->hierro = $hierro;
	}
	
	public function setOro($oro) 
	{
		$this->oro = $oro;
	}
	
	public function setMadera($madera) 
	{
		$this->madera = $madera;
	}
}

//triarii, legio, equites, sagitarii, praetoriani

class Soldiers
{
	private $triarii;
	private $legio;
	private $equites;
	private $sagitarii;
	private $praetoriani;
	
	function __construct($triarii, $legio, $equites, $sagitarii, $praetoriani) 
	{
      	$this->triarii = $triarii;
      	$this->legio = $legio;
      	$this->equites = $equites;
      	$this->sagitarii = $sagitarii;
      	$this->praetoriani = $praetoriani;
   }
	
	public function getTriarii() 
	{
		return $this->triarii;
	}
	
	public function getLegio() 
	{
		return $this->legio;
	}
	
	public function getEquites() 
	{
		return $this->equites;
	}
	
	public function getSagitarii() 
	{
		return $this->sagitarii;
	}
	
	public function getPraetoriani() 
	{
		return $this->praetoriani;
	}
	
	public function setTriarii($triarii) 
	{
		$this->triarii = $triarii;
	}
	
	public function setLegio($legio) 
	{
		$this->legio = $legio;
	}
	
	public function setEquites($equites) 
	{
		$this->equites = $equites;
	}
	
	public function setSagitarii($sagitarii) 
	{
		$this->sagitarii = $sagitarii;
	}
	
	public function setPraetoriani($praetoriani) 
	{
		$this->praetoriani = $praetoriani;
	}
}

/**
 * Cuando un usuario se registra, este algoritmo le asigna una casilla libre.
 * 
 * used by: signup.php
 */
function getNewCityCoord()
{

	$flag=false;
	
	while ($flag==false)
	{
		$x= rand ( 0 ,9 );
		$y= rand ( 0 ,9 );
		if (squareIsFree($x, $y)==TRUE)
		$flag=TRUE;
	}
	
	return new Coordenadas($x,$y);
	
	
}

function squareIsFree($x,$y)
{
	require 'include/dbconnect.php';
	$result = mysql_query("SELECT idcity FROM cities WHERE coordx=".$x." and coordy=".$y);
	 
	if( mysql_num_rows($result) == 0 )
	{
		require 'include/dbdisconnect.php';
		return true;
	}
	else
	{
		require 'include/dbdisconnect.php';
		return false;
	}
}

function  comprobarUsuarioRegistrado($username)
{
	require 'include/dbconnect.php';
	$result = mysql_query("SELECT userID FROM users WHERE username =".$username);
	require 'include/dbdisconnect.php';
	if( !$result )
	{
		return FALSE;
	}
		else return TRUE;
	
}

function getUserCoord() {
	require 'include/dbconnect.php';
	$result = mysql_query("SELECT coordx, coordy FROM cities WHERE idcity = (SELECT idcity FROM users WHERE username = '".$_SESSION["username"]."')" );
	if( !$result )
	{
		die('Error: '. mysql_error());
	}
	$row = mysql_fetch_array($result);
	require 'include/dbdisconnect.php';
	return new Coordenadas($row['coordx'], $row['coordy']);
}

function getEnemyCoord($idcity) 
{
	require 'include/dbconnect.php';
	$result = mysql_query("SELECT coordx, coordy FROM cities WHERE idcity = ".$idcity);
	if( !$result )
	{
		die('Error: '. mysql_error());
	}
	$row = mysql_fetch_array($result);
	require 'include/dbdisconnect.php';
	return new Coordenadas($row['coordx'], $row['coordy']);
}

function isOccupiedCoord($x, $y) {
	require 'include/dbconnect.php';
	$result = mysql_query("SELECT idcity FROM cities WHERE coordx = ".$x." and coordy = ".$y );
	
	if( !$result )
	{
		require 'include/dbdisconnect.php';
		die('Error: '. mysql_error());
	}
	
	if (mysql_num_rows($result) == 1)
	{
		require 'include/dbdisconnect.php';
		return true;
	}
	else if (mysql_num_rows($result) == 0)
	{
		require 'include/dbdisconnect.php';
		return false;
	}
	else
	{
		require 'include/dbdisconnect.php';
		die('Error: el número de ciudades en las coordenadas no es ni 0 ni 1');
	}
}

function getBuilding($x, $y, $idCity) 
{
	require 'include/dbconnect.php';
	
	$box = (4*$x) + $y;
	
	$result = mysql_query("SELECT box".$box.", box".$box."lvl FROM cities WHERE idcity = ".$idCity); 
	
	if( !$result )
	{
		die('Error: '. mysql_error());
	}
	
	$row = mysql_fetch_array($result);
	require 'include/dbdisconnect.php';	
	return new Box($row['box'.$box], $row['box'.$box.'lvl']);
}

function buildBuilding($box, $type, $level, $idCity) 
{
	require 'include/dbconnect.php';
	
	$result = mysql_query("UPDATE cities SET box".$box." = ".$type.", box".$box."lvl = ".$level." WHERE idcity = ".$idCity);
	
	if( !$result )
	{
		die('Error: '. mysql_error());
	}

	require 'include/dbdisconnect.php';	
}

function createSoldiers($idcity, $triarii, $legio, $equites, $sagitarii, $praetoriani) // TODO Igual hay que quitar esta funcion
{
	$soldiers = getSoldiers($_SESSION['idcity'][0]);
	
	require 'include/dbconnect.php';
	
	$triarii += $soldiers->getTriarii();
	$legio += $soldiers->getLegio();
	$equites += $soldiers->getEquites();
	$sagitarii += $soldiers->getSagitarii();
	$praetoriani += $soldiers->getPraetoriani();
	
	$result = mysql_query("UPDATE cities SET tropas0 = ".$triarii.", tropas1 = ".$legio.", tropas2 = ".$equites.", tropas3 = ".$sagitarii.", tropas4 = ".$praetoriani." WHERE idcity = ".$idcity);
	
	if( !$result )
	{
		die('Error: '. mysql_error());
	}

	require 'include/dbdisconnect.php';	
}

function getResources($idcity)
{
	require 'include/dbconnect.php';
	
	$result = mysql_query("SELECT grano, hierro, oro, madera FROM cities WHERE idcity = ".$idcity);
	
	if( !$result )
	{
		die('Error: '. mysql_error());
	}

	$row = mysql_fetch_array($result);
	require 'include/dbdisconnect.php';
	return new Resources($row['grano'], $row['hierro'], $row['oro'], $row['madera']);
}

function getSoldiers($idcity)
{
	require 'include/dbconnect.php';
	
	$result = mysql_query("SELECT tropas0, tropas1, tropas2, tropas3, tropas4 FROM cities WHERE idcity = ".$idcity);
	
	if( !$result )
	{
		die('Error: '. mysql_error());
	}

	$row = mysql_fetch_array($result);
	require 'include/dbdisconnect.php';
	return new Soldiers($row['tropas0'], $row['tropas1'], $row['tropas2'], $row['tropas3'], $row['tropas4']);
}

function getIdCity($i, $j)
{
	require 'include/dbconnect.php';
	
	$result = mysql_query("SELECT idcity FROM cities WHERE coordx = ".$i." AND coordy = ".$j); 
	
	if( !$result )
	{
		die('Error: '. mysql_error());
	}

	$row = mysql_fetch_array($result);
	require 'include/dbdisconnect.php';
	return $row['idcity'];
}

function createAttack($idCityAttacker, $idCityDefender, $nameCityDefender, $triarii, $legio, $equites, $sagitarii, $praetoriani) 
{
	require_once 'include/unidades.php';
	
	$unidades=array($triarii, $legio, $equites, $sagitarii, $praetoriani);
	
	$horiz = $_SESSION["coordx"][0] - getEnemyCoord($idCityDefender)->getCoordX();
	$vert= $_SESSION["coordy"][0] - getEnemyCoord($idCityDefender)->getCoordY();
	$dist= sqrt(($vert*$vert)+($horiz*$horiz));
	
	$time = 0;
	for ($i = 0; $i < 4; $i++) 
	{
		if ($unidades[$i] > 0 && $dist/unidadesGetMovimiento($i) > $time)
		{
			$time = $dist/unidadesGetMovimiento($i);
		}
	}
	
	$time=$time*3600 + time();
	
	require 'include/dbconnect.php';
	
	$result = mysql_query("INSERT INTO attacks (id_ciudad_atacante, id_ciudad_defensor, name_ciudad_defensor, hora_llegada, tropas0, tropas1, tropas2, tropas3, tropas4) VALUES (".$idCityAttacker.", ".$idCityDefender.", '".$nameCityDefender."', ".$time.", ".$triarii.", ".$legio.", ".$equites.", ".$sagitarii.", ".$praetoriani.")");
	
	if( !$result )
	{
		die('Error: '. mysql_error());
	}

	require 'include/dbdisconnect.php';	
}

function searchLastBuilding($idCity)
{
	require 'include/dbconnect.php';
	
	$result = mysql_query("SELECT end_time FROM building WHERE id_city = ".$idCity." ORDER BY idbuilding DESC LIMIT 1"); 
	
	if( !$result )
	{
		die('Error: '. mysql_error());
	}

	$row = mysql_fetch_array($result);
	require 'include/dbdisconnect.php';
	return $row['end_time'];
}

function createBuilding($idCity, $idSquare, $type , $level, $time) 
{
	if (searchLastBuilding($idCity) == NULL) 
	{
		$time += time();
	}
	else
	{
		$time += searchLastBuilding($idCity); 	
	}
	
	
	require 'include/dbconnect.php';
	
	$result = mysql_query("INSERT INTO building (id_city, id_square, type_building, next_level, end_time) VALUES (".$idCity.", ".$idSquare.", ".$type.", ".$level.", ".$time.")"); 
	
	if( !$result )
	{
		die('Error: '. mysql_error());
	}

	require 'include/dbdisconnect.php';	
}

function searchLastCreating($idCity)
{
	require 'include/dbconnect.php';
	
	$result = mysql_query("SELECT end_time FROM creating WHERE id_city = ".$idCity." ORDER BY idcreating DESC LIMIT 1"); 
	
	if( !$result )
	{
		die('Error: '. mysql_error());
	}

	$row = mysql_fetch_array($result);
	require 'include/dbdisconnect.php';
	return $row['end_time'];
}

function createCreating($idCity, $type, $time) 
{
	if (searchLastCreating($idCity) == NULL)
	{
		$time += time();
	}
	else
	{
		$time += searchLastCreating($idCity); 	
	}
	
	
	require 'include/dbconnect.php';
	
	$result = mysql_query("INSERT INTO creating (id_city, end_time, troop_type) VALUES (".$idCity.", ".$time.", ".$type.")"); 
	
	if( !$result )
	{
		die('Error: '. mysql_error());
	}

	require 'include/dbdisconnect.php';	
}

/**
 * Function that shows the resources that are being produced for a given city by time unit.
 * 
 * used by city.php
 */
function searchResources($idCity)
{
	require 'include/dbconnect.php';
	require_once 'include/resources.php';
	
	$resources = getNewResources($_SESSION['iduser'][0]);
	
	return new Resources($resources[0]*360, $resources[1]*360, $resources[2]*360, $resources[3]*360);
}

/**
 * Function that shows the buildings that are being created for a given city.
 * 
 * used by city.php
 */
function searchBuildings($idCity)
{
	require 'include/dbconnect.php';
	require_once 'include/edificios.php';
	
	$result = mysql_query("SELECT type_building, next_level, end_time FROM building WHERE id_city = ".$idCity); 
	
	if( !$result )
	{
		die('Error: '. mysql_error());
	}
	
	while ($row = mysql_fetch_array($result, MYSQL_NUM)) 
	{
    	printf("Tipo de edificio: %s, nivel: %s, tiempo restante: %s <br />", GetName($row[0]), $row[1], tiempo_segundos($row[2]-time()));  
	}
}

/**
 * Function that shows the troops that are being created for a given city.
 * 
 * used by city.php
 */
function searchSoldiers($idCity) 
{
	require 'include/dbconnect.php';
	require_once 'include/unidades.php';
	
	$result = mysql_query("SELECT end_time, troop_type FROM creating WHERE id_city = ".$idCity); 
	
	if( !$result )
	{
		die('Error: '. mysql_error());
	}
		
	$num = 0;
	
	while (($row = mysql_fetch_array($result, MYSQL_NUM)) && ($num < 10)) 
	{
    	printf("Tipo de soldado: %s, tiempo restante: %s <br />", unidadesGetName(0, $row[1]), tiempo_segundos($row[0]-time()));
		$num++;
	}
	
	if ($num == 10)
	{
		printf("<br /> Y %d unidades más", mysql_affected_rows()-10);
	}
}

/**
 * Function that shows the attacks that are pending for a given city.
 * 
 * used by city.php
 */
function searchAttacks($idCity)
{
	require 'include/dbconnect.php';
	
	$result = mysql_query("SELECT name_ciudad_defensor, hora_llegada, tropas0, tropas1, tropas2, tropas3, tropas4 FROM attacks WHERE id_ciudad_atacante = ".$idCity); 
	
	if( !$result )
	{
		die('Error: '. mysql_error());
	}
	
	while ($row = mysql_fetch_array($result, MYSQL_NUM)) 
	{
    	printf("Ciudad: %s, Triarii: %s, Legio: %s, Equites: %s, Sagitarii: %s, Praetoriani: %s, tiempo restante: %s <br />", $row[0], $row[2], $row[3], $row[4], $row[5], $row[6], tiempo_segundos($row[1]-time()));  
	}
}

function searchReturnings($idCity)
{
	require 'include/dbconnect.php';
	
	$result = mysql_query("SELECT hora_llegada, tropas0, tropas1, tropas2, tropas3, tropas4 FROM returning WHERE id_ciudad = ".$idCity); 
	
	if( !$result )
	{
		die('Error: '. mysql_error());
	}
	
	while ($row = mysql_fetch_array($result, MYSQL_NUM)) 
	{
    	printf("Triarii: %s, Legio: %s, Equites: %s, Sagitarii: %s, Praetoriani: %s, tiempo restante: %s <br />", $row[1], $row[2], $row[3], $row[4], $row[5], tiempo_segundos($row[0]-time()));
	}
}

function tiempo_segundos($segundos)
{
	$minutos=$segundos/60;
	$horas=floor($minutos/60);
	$minutos2=$minutos%60;
	$segundos_2=$segundos%60%60%60;
	
	if($minutos2<10)
	{
		$minutos2='0'.$minutos2;
	}
	if($segundos_2<10)
	{
		$segundos_2='0'.$segundos_2;
	}
	
	if($segundos<60)
	{ // segundos
		$resultado= round($segundos).' Segundos';
	}
	elseif($segundos>60 && $segundos<3600)
	{ // minutos
		$resultado= $minutos2.':'.$segundos_2.' Minutos';
	}
	else
	{ // horas 
		$resultado= $horas.':'.$minutos2.':'.$segundos_2.' Horas';
	}
	return $resultado;
}

/**
 * Toma un valor, lo divide por $speed, y redondea hacia arriba.
 * 
 * Usado en unidades.php.
 * @param float $valor
 * @return int
 */
function redondear($valor)
{
	global $speed;
	return ceil($valor/$speed);
}

function isUpgrading($idcity, $idsquare)
{
	require 'include/dbconnect.php';
	$result = mysql_query("SELECT * FROM building WHERE id_city = ".$idcity." AND id_square = ".$idsquare);
	
	if (mysql_num_rows($result) == 1)
	{
		require 'include/dbdisconnect.php';
		return true;
	}
	else if (mysql_num_rows($result) == 0)
	{
		require 'include/dbdisconnect.php';
		return false;
	}
}

function nextLevel($idcity, $idsquare)
{
	require 'include/dbconnect.php';
	$result = mysql_query("SELECT next_level FROM building WHERE id_city = ".$idcity." AND id_square = ".$idsquare);
	
	$row = mysql_fetch_array($result);
	
	require 'include/dbdisconnect.php';
	return $row["next_level"];
}

function discountResources($idcity, $coste)
{
	$recursosActuales = getResources($idcity);
	
	require 'include/dbconnect.php';
	
	$recursosActuales->setGrano($recursosActuales->getGrano() - $coste[0]);
	$recursosActuales->setHierro($recursosActuales->getHierro() - $coste[1]);
	$recursosActuales->setOro($recursosActuales->getOro() - $coste[2]);
	$recursosActuales->setMadera($recursosActuales->getMadera() - $coste[3]);
	
	$result = mysql_query("UPDATE cities SET grano = ".$recursosActuales->getGrano().", hierro = ".$recursosActuales->getHierro().", oro = ".$recursosActuales->getOro().", madera = ".$recursosActuales->getMadera()." WHERE idcity = ".$idcity);
	
	if( !$result )
	{
		die('Error: '. mysql_error());
	}

	require 'include/dbdisconnect.php';	
}

function discountSoldiers($idcity, $soldiers)
{
	$soldadosActuales = getSoldiers($idcity);
	
	require 'include/dbconnect.php';
	
	$soldadosActuales->setTriarii($soldadosActuales->getTriarii() - $soldiers[0]);
	$soldadosActuales->setLegio($soldadosActuales->getLegio() - $soldiers[1]);
	$soldadosActuales->setEquites($soldadosActuales->getEquites() - $soldiers[2]);
	$soldadosActuales->setSagitarii($soldadosActuales->getSagitarii() - $soldiers[3]);
	$soldadosActuales->setPraetoriani($soldadosActuales->getPraetoriani() - $soldiers[4]);
	
	$result = mysql_query("UPDATE cities SET tropas0 = ".$soldadosActuales->getTriarii().", tropas1 = ".$soldadosActuales->getLegio().", tropas2 = ".$soldadosActuales->getEquites().", tropas3 = ".$soldadosActuales->getSagitarii().", tropas4 = ".$soldadosActuales->getPraetoriani()." WHERE idcity = ".$idcity);
	
	if( !$result )
	{
		die('Error: '. mysql_error());
	}

	require 'include/dbdisconnect.php';	
}

function getNamecity($idcity)
{
	require 'include/dbconnect.php';
	
	$result = mysql_query("SELECT namecity FROM cities WHERE idcity = ".$idcity); 
	
	if( !$result )
	{
		die('Error: '. mysql_error());
	}

	$row = mysql_fetch_array($result);
	require 'include/dbdisconnect.php';
	return $row['namecity'];
}

function getNameCityPopUp($i, $j)
{
	require 'include/dbconnect.php';
	
	$result = mysql_query("SELECT namecity FROM cities WHERE coordx = ".$i." AND coordy = ".$j); 
	
	if( !$result )
	{
		die('Error: '. mysql_error());
	}

	$row = mysql_fetch_array($result);
	require 'include/dbdisconnect.php';
	return $row['namecity'];
}

function getNameUserPopUp($i, $j)
{
	require 'include/dbconnect.php';
	
	$result = mysql_query("SELECT username FROM users WHERE iduser = (SELECT iduser FROM cities WHERE coordx = ".$i." AND coordy = ".$j.")"); 
	
	if( !$result )
	{
		die('Error: '. mysql_error());
	}

	$row = mysql_fetch_array($result);
	require 'include/dbdisconnect.php';
	return $row['username'];
}

function stats($stat)
{
	switch ($stat) {
		case "online_time":
			require('include/dbconnect.php');
			$result = mysql_query("SELECT * FROM config"); 
			if( !$result )
			{
				die('Error: '. mysql_error());
			}
			$row = mysql_fetch_array($result);
			require('include/dbdisconnect.php');
			return time() - $row["start_time"];
			
			break;

		case "players":
			require('include/dbconnect.php');
			$result = mysql_query("SELECT * FROM users"); 
			if( !$result )
			{
				die('Error: '. mysql_error());
			} 
			$players = mysql_affected_rows();
			require('include/dbdisconnect.php');
			return $players;
						
			break;
		case "troops":
			require('include/dbconnect.php');
			$result = mysql_query("SELECT * FROM cities"); 
			if( !$result )
			{
				die('Error: '. mysql_error());
			} 
			
			$troops = 0;
			while($row = mysql_fetch_array($result))
			{
				$troops += $row["tropas0"];
				$troops += $row["tropas1"];
				$troops += $row["tropas2"];
				$troops += $row["tropas3"];
				$troops += $row["tropas4"];
			}			
			require('include/dbdisconnect.php');
			return $troops;
			break;
		case "attacks":
			require('include/dbconnect.php');
			$result = mysql_query("SELECT count(*) FROM attacks"); 
			if( !$result )
			{
				die('Error: '. mysql_error());
			}
			$row = mysql_fetch_row($result);
			require('include/dbconnect.php');
			return $row["0"];
			break;
		case "building":
			require('include/dbconnect.php');
			$result = mysql_query("SELECT count(*) FROM building"); 
			if( !$result )
			{
				die('Error: '. mysql_error());
			}
			$row = mysql_fetch_row($result);
			require('include/dbconnect.php');
			return $row["0"];
			break;
		case "creating":
			require('include/dbconnect.php');
			$result = mysql_query("SELECT count(*) FROM creating"); 
			if( !$result )
			{
				die('Error: '. mysql_error());
			}
			$row = mysql_fetch_row($result);
			require('include/dbconnect.php');
			return $row["0"];
			break;
		case "returning":
			require('include/dbconnect.php');
			$result = mysql_query("SELECT count(*) FROM returning"); 
			if( !$result )
			{
				die('Error: '. mysql_error());
			}
			$row = mysql_fetch_row($result);
			require('include/dbconnect.php');
			return $row["0"];
			break;
		default:
			;
		break;
	}
}

function searchHeadQuarter($idcity)
{
	require 'include/dbconnect.php';
	
	$result = mysql_query("SELECT * FROM cities WHERE idcity = ".$idcity); 

	if( !$result )
	{
		die('Error: '. mysql_error());
	}
	
	$column = mysql_fetch_array($result);
	
	$box = 0;
	$encontrado = false;
	
	while (($box < 16) && ($encontrado == false))
	{	
		if ($column["box".$box] == 0)
		{
			$result = mysql_query("SELECT next_level FROM building WHERE id_city = ".$idcity." AND id_square = ".$box);
			
			if (mysql_num_rows($result) == 1)
			{
				$row = mysql_fetch_array($result);
				
				if ($row["next_level"] > 1)
				{
					$encontrado = true;
				}
			}
			else
			{
				$encontrado = true;
			}
		}
		$box++;
	}
		
	require 'include/dbdisconnect.php';
	return $encontrado;
}

function searchMaxLevelHeadQuarter($idcity, $maxLevel)
{
	require 'include/dbconnect.php';
	
	$result = mysql_query("SELECT * FROM cities WHERE idcity = ".$idcity); 

	if( !$result )
	{
		die('Error: '. mysql_error());
	}
	
	$column = mysql_fetch_array($result);
	
	for ($box = 0; $box < 16; $box++) 
	{
		if (($column["box".$box] == 0) && ($column["box".$box."lvl"] > $maxLevel))
		{
			$maxLevel = $column["box".$box."lvl"];
		}
	}
		
	require 'include/dbdisconnect.php';
	return $maxLevel;
}

?>